<template>
  <div class="color-alpha" @mousedown.prevent.stop="selectAlpha">
    <canvas ref="canvasAlphaRef" />
    <div :style="attr.slideAlphaStyle" class="slide" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from "vue"
import { createAlphaSquare, createLinearGradient } from "./composible"

const props = defineProps({
  color: {
    type: String,
    default: "#000000",
  },
  rgba: {
    type: Object,
    default: null,
  },
  width: {
    type: Number,
    default: 15,
  },
  height: {
    type: Number,
    default: 152,
  },
})
const emit = defineEmits(["selectAlpha"])
const canvasAlphaRef = ref()
const attr = reactive({
  slideAlphaStyle: {},
  alphaSize: 5,
})
watch([() => props.color], (newValue, old) => {
  renderColor()
})
watch([() => props.rgba.a], (newValue, old) => {
  renderSlide()
})

onMounted(() => {
  renderColor()
  renderSlide()
})
const renderColor = () => {
  const canvas: any = canvasAlphaRef.value
  const width = props.width
  const height = props.height
  const size = attr.alphaSize
  const canvasSquare = createAlphaSquare(size)
  const ctx = canvas.getContext("2d")
  canvas.width = width
  canvas.height = height
  ctx.fillStyle = ctx.createPattern(canvasSquare, "repeat")
  ctx.fillRect(0, 0, width, height)
  createLinearGradient("p", ctx, width, height, "rgba(255,255,255,0)", props.color)
}
const renderSlide = () => {
  attr.slideAlphaStyle = {
    top: props.rgba.a * props.height - 2 + "px",
  }
}
const selectAlpha = (e: any) => {
  const { top: hueTop } = canvasAlphaRef.value.getBoundingClientRect()
  const mousemove = (e: any) => {
    let y = e.clientY - hueTop
    if (y < 0) {
      y = 0
    }
    if (y > props.height) {
      y = props.height
    }
    let a = parseFloat((y / props.height).toFixed(2))
    emit("selectAlpha", a)
  }
  mousemove(e)
  const mouseup = () => {
    document.removeEventListener("mousemove", mousemove)
    document.removeEventListener("mouseup", mouseup)
  }
  document.addEventListener("mousemove", mousemove)
  document.addEventListener("mouseup", mouseup)
}
</script>

<style scoped lang="scss">
.color-alpha {
  position: relative;
  margin-left: 8px;
  width: 15px;
  cursor: pointer;
  .slide {
    position: absolute;
    left: 0;
    top: 100px;
    width: 100%;
    height: 4px;
    background: #fff;
    box-shadow: 0 0 1px 0 rgba(0, 0, 0, 0.3);
    pointer-events: none;
  }
}
</style>
